package com.sgqing.demo.comfig;


import com.sgqing.demo.entity.SysPermission;
import com.sgqing.demo.entity.SysRole;
import com.sgqing.demo.entity.UserInfo;
import com.sgqing.demo.sevice.UserInfoService;
import org.apache.coyote.http2.ByteUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 进行授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        进行获取用户信息
        UserInfo info = (UserInfo) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
//对用户和角色进行分别的获取，然后添加到SimpleAuthorizationInfo返回
        for (SysRole role : info.getRoleList()) {
//            将角色放到SimpleAuthorizationInfo中
            authorizationInfo.addRole(role.getRole());
            for (SysPermission permission : role.getPermissions()) {
                authorizationInfo.addStringPermission(permission.getPermission());
            }
        }
        return authorizationInfo;
    }

    /**
     * 进行认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

//        首先获取页面传递过来的数据 -- 用户名
        String name = (String) authenticationToken.getPrincipal();
        System.out.println(authenticationToken.getCredentials());
        UserInfo byUsername = userInfoService.findByUsername(name);
        System.out.println(" ByteSource.Util.bytes(byUsername.getCredentialsSalt()):" + ByteSource.Util.bytes(byUsername.getCredentialsSalt()));
        SimpleAuthenticationInfo authenticationInfo =
                new SimpleAuthenticationInfo(
                        name,
                        byUsername.getPassword(),
                        ByteSource.Util.bytes(byUsername.getCredentialsSalt()),
                        getName()
                );
        return authenticationInfo;
    }
}
